package com.haierCamera.customapplication.ui.plan;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.ApiService;
import com.haierCamera.customapplication.api.repo.RegisterRepo;
import com.haierCamera.customapplication.api.vo.GetCameraStatus;
import com.haierCamera.customapplication.common.Resource;
import com.haierCamera.customapplication.databinding.HzklActivityDeviceSetBinding;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.mediaplay.MediaPlayActivity;
import com.lechange.opensdk.api.bean.BreathingLightStatus;
import com.lechange.opensdk.api.bean.FrameReverseStatus;

import javax.inject.Inject;


public class HZKLDeviceSetActivity extends BaseActivity {
    @Inject
    RegisterRepo repo;
    private HzklActivityDeviceSetBinding binding;
    private String tag = "DeviceSetNewActivity";
    private SharedPreferences mSharedPreferences;
    private ToggleButton mSwitch, smartPlan; // 报警订阅开关
    // private ToggleButton mCloudMealBtn; // 云存储套餐开关
    private Button mModifyPwd; //修改设备密码
    private TextView mUpgrade; // 云升级开关
    private String deviceCode;
    private int mCloudMealStates; // 云套餐状态
    private int mAlarmStates; // 报警计划状态
    private boolean mCanBeUpgrade; //设备是否可云升级
    private boolean IsClickSwitchBtn, IsClickSmartBtn; // 是否主动修改动检开关（手势触发）
    private boolean IsClickCloudMealBtn; // 是否主动修改套餐状态 （手势触发）
    private int alarmPlanStatus;
    private int cloudMealStatus;
    private LinearLayout time;
    private ToggleButton lightBtn, imageBtn;
    private boolean IsClickLightSwitchBtn; // 是否主动修改动检开关（手势触发）
    private boolean isClickFrameBtn; // 是否主动修改动检开关（手势触发）
    private RelativeLayout layout;
    private boolean hasPTZAbility = true;
    private String ability;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_device_set);
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mSharedPreferences = getSharedPreferences("OpenSDK", Context.MODE_PRIVATE);
        // 获取通道的UUID
        deviceCode = getIntent().getStringExtra("deviceCode");
        alarmPlanStatus = getIntent().getIntExtra("alarmPlanStatus", 100);
        cloudMealStatus = getIntent().getIntExtra("cloudMealStatus", 100);
        mSwitch = (ToggleButton) findViewById(R.id.switchPlan);
        // mCloudMealBtn = (ToggleButton) findViewById(R.id.cloudMealBtn);
        time = (LinearLayout) findViewById(R.id.movePlanTime);
        lightBtn = (ToggleButton) findViewById(R.id.lightBtn);
        imageBtn = (ToggleButton) findViewById(R.id.imageBtn);
        layout = findViewById(R.id.moveSmart);
        smartPlan = findViewById(R.id.smartPlan);
        //mModifyPwd = (Button) findViewById(R.id.modify_device_pwd);
        // mUpgrade = (TextView) findViewById(R.id.device_upgrade_icon);
        mSwitch.setClickable(false);
        smartPlan.setClickable(false);
        //  mCloudMealBtn.setClickable(false);
        // mUpgrade.setClickable(false);
        initTitle();
        setListener();
        getOriginStatus();

        ability = getIntent().getStringExtra("ability");
        Log.i("TAG","ability-" + ability);
        if (ability!=null&&ability.contains("PT")) {
            hasPTZAbility = true;
        }else {
            hasPTZAbility = false;
        }
        if (hasPTZAbility) {
            getCameraStatus();
            Log.e("ability", "handleMessage:1 " );
            layout.setVisibility(View.VISIBLE);
        }else {
            layout.setVisibility(View.GONE);
            Log.e("ability", "handleMessage:2 ");
        }

//        Business.getInstance().getDeviceInfo2(deviceCode,new Handler(){
//            @Override
//            public void handleMessage(@NonNull Message msg) {
//                super.handleMessage(msg);
//                Log.i("TAG","getDeviceChannel-" + msg.what);
//                if (msg.what == 0) {
//
//
//                   String ability = ((Bundle) msg.obj).getString("ability");
//                    Log.e("ability", "handleMessage: "+ability );
//
//
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (ability!=null&&ability.contains("PT")) {
//                                    hasPTZAbility = true;
//                                }else {
//                                    hasPTZAbility = false;
//                                }
//                                 if (hasPTZAbility) {
//                                      getCameraStatus();
//                                     Log.e("ability", "handleMessage:1 " );
//                                      layout.setVisibility(View.VISIBLE);
//                                  }else {
//                                      layout.setVisibility(View.GONE);
//                                     Log.e("ability", "handleMessage:2 ");
//                                 }
//                                }
//                            });
//
//
//
//
//                } else {
//
//                }
//
//            }
//        });

      /*  getLightStatus();
        getFrameReverseStatus();*/
    }


    /**
     * 初始化标题栏
     */
    public void initTitle() {

    }

    private void getCameraStatus() {
        IsClickSmartBtn = true;
        smartPlan.setClickable(true);
        repo.getCameraStatus(deviceCode, "0", "smartTrack").observe(this, getCameraResource -> {
            switch (getCameraResource.status) {
                case LOADING:
                    //showLoadingDialog();
                    break;
                case ERROR:
                    //dismissLoadingDialog();
                    Toast.makeText(this, getCameraResource.errorMessage, Toast.LENGTH_SHORT).show();
                    break;
                case SUCCESS:
                    //dismissLoadingDialog();
                    GetCameraStatus data = getCameraResource.data;
                    IsClickSmartBtn = false;
                    //状态 1:开,0:关
                    if (data.status.equals("0")) {
                        smartPlan.setChecked(false);
                    } else {
                        smartPlan.setChecked(true);
                    }
                    IsClickSmartBtn = true;
                    break;
            }
        });
    }

    /**
     * 获取初始状态
     */
    @SuppressLint("HandlerLeak")
    private void getOriginStatus() {
        String status = mSharedPreferences.getString("alarmPlan", "");
        if (status != null) {
            mSwitch.setChecked(status.equals("open") ? true : false);
        } else {// 默认没有打开报警订阅
            mSwitch.setChecked(false);
            mSharedPreferences.edit().putString("alarmPlan", "close").commit();
        }
        mSwitch.setVisibility(View.VISIBLE);
        IsClickSwitchBtn = true;
        mSwitch.setClickable(true);

       /* //获取设备动检状态
        Business.getInstance().getAlarmStatus(mChannelUUID, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    if (msg.arg1 == 1) {
                        mSwitch.setChecked(true);
                    } else {
                        mSwitch.setChecked(false);
                    }
                }
            }
        });*/
        // 初始化数据
        Log.i("TAG", "getDeviceInfo");
        Business.getInstance().getDeviceInfo(deviceCode, new Handler() {
            @SuppressWarnings("unchecked")
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle bundle = (Bundle) msg.obj;
                if (msg.what == 0) {

                    mAlarmStates = bundle.getInt("alarmStatus");
                    mCloudMealStates = bundle.getInt("cloudStatus");
                    mCanBeUpgrade = bundle.getBoolean("canBeUpgrade");

                    if (mCloudMealStates == 1) {
                        IsClickCloudMealBtn = false;
                        //  mCloudMealBtn.setChecked(true);
                    }
                    if (mAlarmStates == 1) {
                        IsClickSwitchBtn = false;
                        mSwitch.setChecked(true);
                    }

                    if (!mCanBeUpgrade) {
                        // mUpgrade.setVisibility(View.INVISIBLE);
                    }

                    mSwitch.setVisibility(View.VISIBLE);
                    // mCloudMealBtn.setVisibility(View.VISIBLE);

                } else {
                    Toast.makeText(HZKLDeviceSetActivity.this, "获取初始状态信息失败",
                            Toast.LENGTH_SHORT).show();
                }

                IsClickCloudMealBtn = true;
                IsClickSwitchBtn = true;
                mSwitch.setClickable(true);
                // mCloudMealBtn.setClickable(true);
                //  mUpgrade.setClickable(true);
            }
        });

    }

    /**
     * 设置监听函数
     */
    public void setListener() {
        time.setOnClickListener(v -> {
            Intent intent = new Intent(HZKLDeviceSetActivity.this, HZKLPlanTimeSettingActivity.class);
            intent.putExtra("deviceCode", deviceCode);
            startActivity(intent);
        });
        mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton view, boolean state) {

                Log.i("TAG", "onCheckedChanged-" + "IsClickSwitchBtn-" + IsClickSwitchBtn + "/state-" + state);
                // 如果是手势触发，则进行网络请求
                if (IsClickSwitchBtn) {
                    modifyAlarmPlan(state);
                }

            }
        });

        smartPlan.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton view, boolean state) {

                Log.i("TAG", "onCheckedChanged-" + "IsClickSwitchBtn-" + IsClickSwitchBtn + "/state-" + state);
                // 如果是手势触发，则进行网络请求
                if (IsClickSmartBtn) {
                    setCamera(state);
                }

            }
        });

      /*  lightBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (IsClickLightSwitchBtn) {
                    setLightStatus(isChecked);
                }
            }
        });
        imageBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isClickFrameBtn) {
                    setFrameReverseStatus(isChecked);
                }
            }
        });
        mCloudMealBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton view, boolean state) {
                // 如果是手势触发，则进行网络请求
                if (IsClickCloudMealBtn) {
                    //暂不支持此功能
//					Toast.makeText(DeviceSetNewActivity.this, "Not support now", Toast.LENGTH_SHORT).show();
                    setStorageStrategy(state);
                }
            }
        });*/

		/*mModifyPwd.setOnClickListener(new OnClickListener() {
            @Override
			public void onClick(View v) {
				modifyDevicePassword();
			}
		});*/

        /*mUpgrade.setOnClickListener(v -> {
            // TODO Auto-generated method stub
            if (!mCanBeUpgrade) {
                Toast.makeText(HZKLDeviceSetActivity.this, "已是最新版本无需更新", Toast.LENGTH_SHORT).show();
                return;
            }

            //UpgradeDevice();
        });*/
    }

    private String status;

    private void setCamera(boolean state) {
        smartPlan.setClickable(false);
        //开关 0:关 1开
        if (state) {
            status = "1";
        } else {
            status = "0";
        }
        repo.setCameraStatus(deviceCode, "0", "smartTrack", status).observe(this, objectResource -> {
            switch (objectResource.status) {
                case LOADING:
                    showLoadingDialog();
                    break;
                case ERROR:
                    dismissLoadingDialog();
                    Toast.makeText(HZKLDeviceSetActivity.this, objectResource.errorMessage, Toast.LENGTH_SHORT).show();
                    IsClickSmartBtn = false;
                    smartPlan.setChecked(!state);
                    break;
                case SUCCESS:
                    dismissLoadingDialog();
                    IsClickSmartBtn = false;
                    smartPlan.setChecked(state);
                    Toast.makeText(this, "设置成功", Toast.LENGTH_SHORT).show();
                    break;
            }
            IsClickSmartBtn = true;
            smartPlan.setClickable(true);
        });
    }

    private void getLightStatus() {
        Business.getInstance().getLightStatus(deviceCode, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    BreathingLightStatus.ResponseData data = ((BreathingLightStatus.Response) (((Business.RetObject) msg.obj).resp)).data;
                    if (data.status.equals("on")) {
                        IsClickLightSwitchBtn = false;
                        lightBtn.setChecked(true);
                    } else {
                        IsClickLightSwitchBtn = false;
                        lightBtn.setChecked(false);
                    }
                } else {
                    Toast.makeText(HZKLDeviceSetActivity.this, ((Business.RetObject) msg.obj).mMsg, Toast.LENGTH_SHORT).show();
                }
                IsClickLightSwitchBtn = true;
            }
        });
    }

    private void setLightStatus(final boolean isChecked) {
        lightBtn.setClickable(false);
        String stats;
        if (isChecked) {
            stats = "on";
        } else {
            stats = "off";
        }
        Business.getInstance().ModifyBreat(deviceCode, stats, new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == 0) {
                            Toast.makeText(HZKLDeviceSetActivity.this, ((Business.RetObject) msg.obj).mMsg, Toast.LENGTH_SHORT).show();
                        } else {
                            IsClickLightSwitchBtn = false;
                            lightBtn.setChecked(!isChecked);
                            Toast.makeText(HZKLDeviceSetActivity.this, ((Business.RetObject) msg.obj).mMsg, Toast.LENGTH_SHORT).show();
                        }
                        IsClickLightSwitchBtn = true;
                        lightBtn.setClickable(true);
                    }
                }
        );
    }

    private void getFrameReverseStatus() {
        if (null == deviceCode) {
            Toast.makeText(this, "ChannelInfo为null", Toast.LENGTH_SHORT).show();
            return;
        }
        Business.getInstance().getFrameReverseStatus(deviceCode, "0", new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    FrameReverseStatus.ResponseData data = ((FrameReverseStatus.Response) (((Business.RetObject) msg.obj).resp)).data;
                    if (data.direction.equals("reverse")) {
                        isClickFrameBtn = false;
                        imageBtn.setChecked(true);
                    } else {
                        isClickFrameBtn = false;
                        imageBtn.setChecked(false);
                    }
                } else {
                    Toast.makeText(HZKLDeviceSetActivity.this, ((Business.RetObject) msg.obj).mMsg, Toast.LENGTH_SHORT).show();
                }
                isClickFrameBtn = true;
            }
        });
    }

    private void setFrameReverseStatus(final boolean isChecked) {
        imageBtn.setClickable(false);
        String stats;
        if (isChecked) {
            stats = "reverse";
        } else {
            stats = "normal";
        }
        Business.getInstance().ModifyFrameReverse(deviceCode, "0", stats, new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == 0) {
                            Toast.makeText(HZKLDeviceSetActivity.this, ((Business.RetObject) msg.obj).mMsg, Toast.LENGTH_SHORT).show();
                        } else {
                            isClickFrameBtn = false;
                            imageBtn.setChecked(!isChecked);
                            Toast.makeText(HZKLDeviceSetActivity.this, ((Business.RetObject) msg.obj).mMsg, Toast.LENGTH_SHORT).show();
                        }
                        isClickFrameBtn = true;
                        imageBtn.setClickable(true);
                    }
                }
        );
    }


    /**
     * 设置云套餐状态
     * <p>
     * 开启关闭状态
     */
    @SuppressLint("HandlerLeak")
    public void setStorageStrategy(final boolean state) {

        //  mCloudMealBtn.setClickable(false);
        String states = null;
        if (state) {
            states = "on";
        } else {
            states = "off";
        }
        Business.getInstance().setStorageStartegy(states, deviceCode,
                new Handler() {

                    @Override
                    public void handleMessage(Message msg) {
                        if (0 == msg.what) {
                            Toast.makeText(
                                    HZKLDeviceSetActivity.this,
                                    "云套餐更改成功",
                                    Toast.LENGTH_SHORT).show();
                        } else {

                            Toast.makeText(
                                    HZKLDeviceSetActivity.this, (String) msg.obj,
                                    Toast.LENGTH_SHORT).show();
                            IsClickCloudMealBtn = false;
                            //  mCloudMealBtn.setChecked(!state);
                        }
                        IsClickCloudMealBtn = true;
                        // mCloudMealBtn.setClickable(true);
                    }
                });
    }

    /**
     * 修改动检计划状态
     *
     * @param enable 动检计划开启与否
     */
    @SuppressLint("HandlerLeak")
    public void modifyAlarmPlan(final boolean enable) {
        Log.i("TAG", "modifyAlarmPlan");
        mSwitch.setClickable(false);
        Business.getInstance().modifyAlarmStatus(enable, deviceCode,
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        Log.i("TAG", "what-" + msg.what);
                        if (0 == msg.what) {
                            Toast.makeText(HZKLDeviceSetActivity.this,
                                    "修改动检计划成功",
                                    Toast.LENGTH_LONG).show();

                            mSharedPreferences
                                    .edit()
                                    .putString("alarmPlan", enable ? "open" : "close").commit();
                            if (hasPTZAbility){
                                getCameraStatus();
                           }
                            if (enable) {
                                if (hasPTZAbility) {
                                    layout.setVisibility(View.VISIBLE);
                                    Log.e("ability", "handleMessage:3 ");
                                }else {
                                    layout.setVisibility(View.GONE);
                                    Log.e("ability", "handleMessage:4 ");
                                }
                            } else {
                                layout.setVisibility(View.GONE);
                                Log.e("ability", "handleMessage:5 ");
                            }
                        } else {
                            if (msg.obj != null) {
                                Toast.makeText(HZKLDeviceSetActivity.this,
                                        ((Business.RetObject) msg.obj).mMsg,
                                        Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(HZKLDeviceSetActivity.this,
                                        "操作失败",
                                        Toast.LENGTH_LONG).show();
                            }
                            IsClickSwitchBtn = false;
                            mSwitch.setChecked(!enable);
                        }
                        IsClickSwitchBtn = true;
                        mSwitch.setClickable(true);
                    }

                });
    }

    /* *//**
     * 修改设备密码
     *//*
    public void modifyDevicePassword() {
        LinearLayout layout = (LinearLayout) LinearLayout.inflate(this, R.layout.dialog_modify_device_password, null);
        final EditText oldPwd = (EditText) layout.findViewById(R.id.old_pwd);
        final EditText newPwd = (EditText) layout.findViewById(R.id.new_pwd);
        new AlertDialog.Builder(DeviceSetActivity.this)
                .setTitle(R.string.alarm_message_keyinput_dialog_title)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(layout)
                .setPositiveButton(R.string.dialog_positive,
                        new android.content.DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                String oldKey = oldPwd.getText().toString();
                                String newKey = newPwd.getText().toString();
                                String deviceId = Business.getInstance().getChannel(deviceCode).getDeviceCode();

                                Business.getInstance().modifyDevicePwd(deviceId, oldKey, newKey, new Handler() {
                                    @Override
                                    public void handleMessage(Message msg) {
                                        Business.RetObject retObject = (Business.RetObject) msg.obj;
                                        if (msg.what == 0) {
                                            Toast.makeText(DeviceSetActivity.this, "modigyDevicePwd success", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(DeviceSetActivity.this, retObject.mMsg, Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }
                        }).setNegativeButton(R.string.dialog_nagative, null).show();
    }
*/
    /**
     * 设备云升级
     *//*
    public void UpgradeDevice() {

        mUpgrade.setClickable(false);
        Business.getInstance().upgradeDevice(deviceCode, new Handler() {

            @Override
            public void handleMessage(Message msg) {
                if (0 == msg.what) {
                    Toast.makeText(DeviceSetActivity.this,
                            R.string.toast_cloudupdate_success,
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(DeviceSetActivity.this,
                            msg.obj.toString(),
                            Toast.LENGTH_LONG).show();
                }
                mUpgrade.setClickable(true);
            }

        });
    }*/
}
